package cn.gztang.controller;

import cn.gztang.constant.ErrorCode;
import cn.gztang.constant.QRCodeInfo;
import cn.gztang.entity.dto.GasTankUpdate;
import cn.gztang.entity.dto.PageQuery;
import cn.gztang.entity.dto.ResultBean;
import cn.gztang.entity.po.GasTankInfo;
import cn.gztang.entity.vo.UserInfoVO;
import cn.gztang.exception.QRCodeCreateFailException;
import cn.gztang.exception.ZipCodeFailException;
import cn.gztang.service.GasTankService;
import cn.gztang.util.*;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static cn.gztang.constant.UserType.*;

/**
 * @author GaoFeng2017
 * @date 2018/9/6 19:25
 */
@Controller
public class GasTankController {

    @Autowired
    private GasTankService gasTankService;

    private static Logger logger = LoggerFactory.getLogger(GasTankController.class);

    @RequestMapping("/gas-tank/code/image/download")
    public void getCodeImage(HttpSession session, HttpServletResponse response, @RequestParam long begin , @RequestParam long end) {

        int beginLength = (begin + "").length();
        int endLength = (end + "").length();
        if ((beginLength != 13 || endLength != 13) ) {
            throw new ZipCodeFailException("条码长度必须为13", ErrorCode.INVALID_REQUEST_PARAM);
        }

        long diff = end - begin;
        int count = (int) (diff + 1);

        if (begin > end || diff >= 500) {
            throw new ZipCodeFailException("请输入正确的条码范围，打包的条码个数不得超过500", ErrorCode.INVALID_REQUEST_PARAM);
        }

        // 验证权限
        UserInfoVO userInfoVO = (UserInfoVO) session.getAttribute(LOGIN_INFO);
        ValidateUtil.checkAccess(userInfoVO.getType(),SUPER_ADMIN_TYPE,ADMIN_TYPE, QRCODE_MANAGER_TYPE);


        List<Long> exitsBarcodeByRange = gasTankService.findExitsBarcodeByRange(begin, end);
        List<Long> allBarcode = new ArrayList<>(count - exitsBarcodeByRange.size());

        for (long i = begin;i <= end;i++) {
            allBarcode.add(i);
        }

        if (ValidateUtil.checkCollection(exitsBarcodeByRange)) {
            allBarcode.removeAll(exitsBarcodeByRange);
        }

        int addCount = gasTankService.addGasTankInfo(allBarcode);

        if (addCount != allBarcode.size()) {
            throw new ZipCodeFailException("条形码生成失败，请稍后再试", ErrorCode.DATA_ADD_FAIL);
        }

        try {

            String parentPath = session.getServletContext().getRealPath(QRCodeInfo.QRCODE_IMAGE_UPLOAD_DIR);
            String zipFilePath = begin + "-" + end + "--二维码和条形码.zip";
            String realPath = parentPath + "/" + zipFilePath;

            gasTankService.zipCodeImage(begin,end,parentPath,realPath,count);

            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(zipFilePath, "utf-8"));
            response.setHeader(HttpHeaders.CONTENT_TYPE,"application/octet-stream");
            ZipUtil.fileWriteToResponse(response, realPath);

        } catch (QRCodeCreateFailException | IOException e) {
            logger.error("二维码打包异常,{}", e, e.getMessage());
            throw new ZipCodeFailException("二维码打包失败，请稍后再试", ErrorCode.IO_EXCEPTION);
        }

    }

    /*@RequestMapping("/gas-tank/code/image/upload")
    @ResponseBody*/
    public Object uploadCodeImage(MultipartFile[] files, HttpServletRequest request, HttpSession session) {

        ValidateUtil.checkArrayParam(files);
        String filePath = request.getServletContext().getRealPath("WEB-INF/upload/") + DateUtil.getSecond() / 3600;
        FileUtil.createDirectory(filePath);

        // 验证权限
        UserInfoVO userInfoVO = (UserInfoVO) session.getAttribute(LOGIN_INFO);
        ValidateUtil.checkAccess(userInfoVO.getType(),SUPER_ADMIN_TYPE,ADMIN_TYPE, QRCODE_MANAGER_TYPE);

        for (MultipartFile file : files) {
            try {
                file.transferTo(new File(filePath + "/" + file.getOriginalFilename()));
            } catch (IOException e) {
                return new ResultBean<>(false, ErrorCode.IO_EXCEPTION,"上传失败");
            }
        }

        return new ResultBean<>("上传成功");
    }

    @RequestMapping("/gas/info/{barcode}")
    @ResponseBody
    public Object getCodeInfoByBarcode(@PathVariable("barcode") long barcode, HttpSession session) {

        if (barcode <= 0) {
            return new ResultBean<>("请求参数错误");
        }

        GasTankInfo gasTankInfo = gasTankService.findByBarcode(barcode);

        return new ResultBean<>(gasTankInfo);
    }

    @RequestMapping("/gas/{barcode}")
    public String getCodeInfoView(@PathVariable("barcode") long barcode, Model model) {
        model.addAttribute("barcode",barcode);
        return "forward:/info.jsp";
    }

    @RequestMapping("/gas-tank/update")
    @ResponseBody
    public Object updateGasTankInfo(HttpSession session, @RequestBody GasTankUpdate tankUpdate) {
        // 验证权限
        UserInfoVO userInfoVO = (UserInfoVO) session.getAttribute(LOGIN_INFO);
        Byte type = userInfoVO.getType();
        ValidateUtil.checkAccess(type,SUPER_ADMIN_TYPE, ADMIN_TYPE, CREATOR_TYPE);

        if (Objects.equals(type,CREATOR_TYPE)) {
            // 校检
            GasTankInfo gasTankInfo = gasTankService.findById(tankUpdate.getId());
            if (gasTankInfo.getIsUpdate() == 1) {
                return new ResultBean<>(false,ErrorCode.DATA_UPDATE_FAIL,"更新失败，当前信息只能被更新一次");
            }
        }

        return new ResultBean<>(gasTankService.updateGasTank(tankUpdate));
    }

    @RequestMapping("/gas-tank/all/list")
    @ResponseBody
    public Object getAllGasTank(HttpSession session, @RequestBody(required = false) PageQuery pageQuery) {

        // 验证权限
        UserInfoVO userInfoVO = (UserInfoVO) session.getAttribute(LOGIN_INFO);
        ValidateUtil.checkAccess(userInfoVO.getType(),SUPER_ADMIN_TYPE,ADMIN_TYPE);

        pageQuery = POJOUtil.getPageQuery(pageQuery);
        List<GasTankInfo> allByPageQuery = gasTankService.findAllByPageQuery(pageQuery);

        return new ResultBean<>(new PageInfo<>(allByPageQuery));
    }

}
